import 'package:flutter/material.dart';
import 'package:flutter_boost/boost_navigator.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/src/header/refresh_indicator.dart';
import 'package:flutter_module/api/cooperation_request.dart';
import 'package:flutter_module/api/dic_requset.dart';
import 'package:flutter_module/common/base/base_list.dart';
import 'package:flutter_module/common/base/base_page.dart';
import 'package:flutter_module/model/cooperation_address_mo.dart';
import 'package:flutter_module/model/cooperation_list_mo.dart';
import 'package:flutter_module/model/dic_mo.dart';
import 'package:flutter_module/page/cooperation/widgets/cooperation_list_mask_view.dart';
import 'package:flutter_module/page/cooperation/widgets/cooperation_list_row.dart';
import 'package:flutter_module/page/cooperation/widgets/cooperation_list_topbar.dart';
import 'dart:ui';

import 'package:flutter_module/routers.dart';
import 'package:flutter_module/style/colors.dart';

enum CooperationListType {
  all,
  serverObject,
  area,
}

class CooperationListPage extends BaseStateFulWidget {
  const CooperationListPage({Key? key}) : super(key: key);

  @override
  // BaseState<StatefulWidget>
  BaseState<StatefulWidget> buildState() {
    return _CooperationListPageState();
  }
}

class _CooperationListPageState extends BaseState<CooperationListPage>
    with BasePage, ListBehavior, TickerProviderStateMixin {
  // 行数据
  List<CooperationListItemMo> _rowItems = [];
  // 服务对象代码
  String targetCode = "";
  // 省
  String province = "";
  //页数
  int page = 0;
  // 总页数
  int totalPage = 10000;
  // 是否显示遮罩
  bool isShowMask = false;

  int selectedCategory = CooperationListType.all.index;
  //服务对象数组
  List<CooperationListMaskItem> serverObjects = [];
  // 地区数组
  List<CooperationListMaskItem> areas = [];

  //遮罩弹出层
  OverlayEntry? overlayEntry;

  final GlobalKey<CooperationListTopBarState> tobBarKey = GlobalKey();

  @override
  void initState() {
    _getCooperationList();
    _getAddressList();
    _getServerOjects();

    super.initState();
  }

  @override
  void dispose() {
    _disMissOverLayer();
    super.dispose();
  }

  @override
  String get appBarTitle => '合作服务商';

  @override
  createAppBar() {
    return AppBar(
      backgroundColor: Colors.white,
      elevation: 0,
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: onBack,
        iconSize: 20.0,
        padding: EdgeInsets.only(left: 16.0),
        alignment: Alignment.centerLeft,
        color: ThemeColors.text333,
      ),
      centerTitle: true,
      title: Text(
        appBarTitle,
        style: TextStyle(
          color: ThemeColors.text333,
          fontSize: 17.0,
          fontWeight: FontWeight.w500,
        ),
      ),
      actions: getActions(),
      bottom: CooperationListTopBar(
          key: tobBarKey,
          didSelect: (index) {
            bool isSame = index == selectedCategory;
            if (index == CooperationListType.all.index) {
              // 点击全部a
              _disMissOverLayer();
              //重置两个组数据的选中状态
              setState(() {
                serverObjects.map((e) => e..select = false);
                areas.map((e) => e..select = false);
              });

              province = "";
              targetCode = "";
              page = 1;
              _getCooperationList();
            } else {
              //  点击 服务商 或者 地区
              selectedCategory = index;
              if (isSame && isShowMask) {
                _disMissOverLayer();
              } else {
                _showOverLay();
              }
            }
          }),
    );
  }

  @override
  Widget createView(BuildContext context) {
    return ListView.builder(
      shrinkWrap: true,
      itemCount: _rowItems.length,
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: () {
            BoostNavigator.instance.push(CooperationRouters.HOME,
                arguments: {'companyId': _rowItems[index].id.toString()});
          },
          child: CooperationLisRow(item: _rowItems[index]),
        );
      },
    );
  }

  @override
  OnRefreshCallback get onRefresh => () async {
        page = 1;
        _getCooperationList();
      };

  @override
  OnRefreshCallback get onLoad => () async {
        page += 1;
        _getCooperationList();
      };

  // 显示弹出层
  void _showOverLay() {
    if (isShowMask) {
      _disMissOverLayer();
    }

    overlayEntry = OverlayEntry(builder: (content) {
      return Container(
        margin: EdgeInsets.fromLTRB(
            0,
            kBottomNavigationBarHeight +
                MediaQueryData.fromWindow(window).padding.top +
                60,
            0,
            0),
        child: CooperationListMaskView(
            items: selectedCategory == CooperationListType.serverObject.index
                ? this.serverObjects
                : this.areas,
            sureSeletItems: (items) {
              tobBarKey.currentState?.reset();
              _disMissOverLayer();
              this.isShowMask = false;
              if (selectedCategory == CooperationListType.serverObject.index) {
                targetCode = items.map((e) => e.id).join(",");
                page = 1;
                _getCooperationList();
              } else {
                province = items.map((e) => e.id).join(",");
                page = 1;
                _getCooperationList();
              }
            }),
      );
    });

    isShowMask = true;
    Overlay.of(context)!.insert(overlayEntry!);
  }

  // 隐藏弹出层
  void _disMissOverLayer() {
    if (isShowMask) {
      overlayEntry?.remove();
      isShowMask = false;
    }
  }

  // 请求服务对象
  void _getServerOjects() async {
    DicRequest req = DicRequest(type: DicType.SERVICE_PROVIDER);
    try {
      List<dynamic> result = await req.fire(this);

      List<DicItemMo> dicModes = dicListFormMap(result);
      serverObjects = dicModes
          .map((e) => CooperationListMaskItem(
              id: e.dictCode ?? "", title: e.dictName ?? ""))
          .toList();
    } catch (e) {
      print(e);
    }
  }

  //请求地域数据
  void _getAddressList() async {
    CooperationAddressRequest req = new CooperationAddressRequest();
    try {
      List<dynamic> result = await req.fire(this);

      List<CooperationAddressIemMo> areaModels =
          result.map((e) => CooperationAddressIemMo.fromMap(e)).toList();
      areas = areaModels
          .map((e) => CooperationListMaskItem(
              id: e.provinceId.toString(), title: e.shortName ?? ""))
          .toList();
    } catch (e) {
      print(e);
    }
  }

  // 请求列表数据
  void _getCooperationList() async {
    CooperationListReuest req = new CooperationListReuest();
    req.addQurey('pageNum', page);
    if (province.length > 0) {
      req.addQurey("province", province);
    }
    if (targetCode.length > 0) {
      req.addQurey("targetCode", targetCode);
    }
    isLoading = true;
    try {
      var result = await req.fire(this);
      var datas = CooperationListMo.fromJson(result);
      List<CooperationListItemMo> items = datas.data ?? [];

      if (page == 1) {
        _rowItems.clear();
      }

      totalPage = datas.totalPage ?? 0;

      setState(() {
        _rowItems.addAll(items);
        isLoading = false;
        if (page == 1 && _rowItems.length <= 0) {
          isEmpty = true;
        } else {
          isEmpty = false;
        }
      });

      esRefreshController.finishRefresh(success: true);
      esRefreshController.finishLoad(success: true);
      if (page == totalPage) {
        esRefreshController.finishLoad(noMore: true);
      }
    } catch (e) {
      isLoading = false;
    }
  }
}
